import { Space, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import React, { useEffect, useState } from 'react';
import { stuList, deleteStudent } from '@/api/stu';

interface DataType {
  objectId: string;
  name: string;
  score: number;
  address: string;
  birthday: string;
}

const StuList: React.FC = () => {
  const [data, setData] = useState<DataType[]>([]);

  const columns: ColumnsType<DataType> = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '分数',
      dataIndex: 'score',
      key: 'score',
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '生日',
      key: 'birthday',
      dataIndex: 'birthday',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record, index) => (
        <Space size="middle">
          <a>新增</a>
          <a
            onClick={async () => {
              await deleteStudent(record.objectId);
              const res = await stuList();
              setData(res.results);
            }}
          >
            删除
          </a>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await stuList();
        setData(res.results);
      } catch (error) {
        console.error('获取学生列表失败:', error);
      }
    };

    fetchData();
  }, []);

  return <Table columns={columns} dataSource={data} rowKey="objectId" />;
};

export default StuList;
